package com.example.flutter_desbase64_plugin;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class DESBase64Util {
    /**
     * 密码长度必须是8的倍数
     */
    public final static String KEY = "RSAdes123456789whsjzd123";

    /**
     * 加密方式
     */
    public final static String DES = "DES";

    /**
     * 默认编码
     */
    public final static String ENCODING = "UTF-8";

    /**
     * DES加密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密匙数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        // 现在，获取数据并加密
        // 正式执行加密操作
        return cipher.doFinal(src);
    }

    /**
     * DES解密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        // 现在，获取数据并解密
        // 正式执行解密操作
        return cipher.doFinal(src);
    }

    /**
     * BASE64编码
     *
     * @param info
     * @return
     */
    public static String base64Encode(byte[] info) {
        return Base64.encodeToString(info, Base64.DEFAULT);
    }

    /**
     * BASE64解码
     * *
     *
     * @param info
     * @return
     */
    public static byte[] base64Decode(String info) {
        return Base64.decode(info, Base64.DEFAULT);
    }

    /**
     * 先对消息体进行DES编码再进行BASE64编码
     *
     * @param info
     * @return
     */
    public static String encodeInfo(String info) {
        try {
            byte[] temp = encrypt(info.getBytes(ENCODING),
                    KEY.getBytes(ENCODING));
            return base64Encode(temp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 先对消息体进行BASE64解码再进行DES解码
     *
     * @param info
     * @return
     */
    public static String decodeInfo(String info) {
        byte[] temp = base64Decode(info);
        try {
            byte[] buf = decrypt(temp,
                    KEY.getBytes(ENCODING));
            return new String(buf,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字符串gzip压缩
     */
    public static String gzip(String primStr) {
        if (primStr == null || primStr.length() == 0) {
            return primStr;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(primStr.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Base64.encodeToString(out.toByteArray(),Base64.DEFAULT);
    }

    /**
     * 字符串的解压
     */
    public static String jyZip(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        GZIPInputStream ginzip = null;
        byte[] compressed = null;
        String decompressed = null;
        try {
            compressed = Base64.decode(compressedStr,Base64.DEFAULT);
            in = new ByteArrayInputStream(compressed);
            ginzip = new GZIPInputStream(in);

            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ginzip != null) {
                try {
                    ginzip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return decompressed;
    }

    public static String jyZipAndDecodeInfo(String sourceStr) {
        try {
            String jyZipString = jyZip(sourceStr);
            String decodeString = decodeInfo(jyZipString);
            return decodeString;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return sourceStr;
    }

    public static String gZipAndEncodeInfo(String sourceStr) {
        try {
            String encodeString = encodeInfo(sourceStr);
            String zipString = gzip(encodeString);
            return zipString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sourceStr;
    }
}
